package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.text.StrFormatter;
import com.budwk.app.jim.SqfwWebSocket;
import com.budwk.app.jim.WebSocketMsgDTO;
import com.budwk.app.sqfw.constants.SqfwCloudBusinessConstants;
import com.budwk.app.sqfw.constants.SqfwWebSocketMsgConstants;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_servicerecord;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.tencent.TCyysb;
import com.budwk.app.util.AudioToTextUtils;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.budwk.app.sqfw.models.Sqfw_cloudcallback;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.adaptor.WhaleAdaptor;
import org.nutz.mvc.annotation.*;
import org.nutz.lang.Strings;
import com.budwk.starter.common.openapi.annotation.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@IocBean
@At("/platform/sqfw/cloudcallback")
@ApiDefinition(tag = "语音识别回调")
@Slf4j
public class SqfwCloudcallbackController {
    @Inject
    private SqfwCloudcallbackService sqfwCloudcallbackService;
    @Inject
    private SqfwServicerecordService sqfwServicerecordService;
    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;
    @Inject
    private SqfwWebSocket sqfwWebSocket;
    @Inject
    private SqfwTextReplaceService sqfwTextReplaceService;
    @Inject
    private HuaweiOssService huaweiOssService;
    @Inject
    private PropertiesProxy propertiesProxy;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询语音识别回调")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_cloudcallback.class
    )
    @ApiResponses(
            implementation = Sqfw_cloudcallback.class
    )
    @SaCheckLogin
    public Result<?> list(@Param("..") Sqfw_cloudcallback bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        }

        if (bean.getCode() != null && Strings.isNotBlank(bean.getCode().toString())) {
            cnd.and("code", "like", "%" + bean.getCode() + "%");
        }

        if (bean.getMessage() != null && Strings.isNotBlank(bean.getMessage().toString())) {
            cnd.and("message", "like", "%" + bean.getMessage() + "%");
        }

        if (bean.getRequestId() != null && Strings.isNotBlank(bean.getRequestId().toString())) {
            cnd.and("requestId", "like", "%" + bean.getRequestId() + "%");
        }

        if (bean.getAppid() != null && Strings.isNotBlank(bean.getAppid().toString())) {
            cnd.and("appid", "like", "%" + bean.getAppid() + "%");
        }

        if (bean.getProjectid() != null && Strings.isNotBlank(bean.getProjectid().toString())) {
            cnd.and("projectid", "like", "%" + bean.getProjectid() + "%");
        }

        if (bean.getAudioUrl() != null && Strings.isNotBlank(bean.getAudioUrl().toString())) {
            cnd.and("audioUrl", "like", "%" + bean.getAudioUrl() + "%");
        }

        if (bean.getText() != null && Strings.isNotBlank(bean.getText().toString())) {
            cnd.and("text", "like", "%" + bean.getText() + "%");
        }

        if (bean.getResultDetail() != null && Strings.isNotBlank(bean.getResultDetail().toString())) {
            cnd.and("resultDetail", "like", "%" + bean.getResultDetail() + "%");
        }

        if (bean.getAudioTime() != null && Strings.isNotBlank(bean.getAudioTime().toString())) {
            cnd.and("audioTime", "like", "%" + bean.getAudioTime() + "%");
        }

        return Result.data(sqfwCloudcallbackService.listPage(pageNo, pageSize, cnd));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增语音识别回调")
    @ApiFormParams(
            implementation = Sqfw_cloudcallback.class
    )
    @ApiResponses
    @SLog(tag = "新增语音识别回调", value = "${args[0].id}")
    @SaCheckLogin
    public Result<?> create(@Param("..") Sqfw_cloudcallback sqfwCloudcallback, HttpServletRequest req) {
        sqfwCloudcallback.setCreatedBy(SecurityUtil.getUserId());
        sqfwCloudcallbackService.insert(sqfwCloudcallback);
        return Result.success();
    }

    @At
    @Ok("json")
    @ApiOperation(name = "腾讯云语音识别回调")
    @ApiFormParams(
            implementation = Sqfw_cloudcallback.class
    )
    @ApiResponses
    @SLog(tag = "腾讯云语音识别回调",value = "${args[0]}")
    @AdaptBy(type = WhaleAdaptor.class)
    public Result<?> callback(@Param("..") Sqfw_cloudcallback sqfwCloudcallback, HttpServletRequest req) {

        if (StringUtils.isBlank(sqfwCloudcallback.getRequestId())) return Result.success();

        Cnd cnd = Cnd.NEW();
        cnd.and("taskId", "=", sqfwCloudcallback.getRequestId());
        Sqfw_servicerecord bean = sqfwServicerecordService.fetch(cnd);

        String replaceText = sqfwTextReplaceService.replaceText(sqfwCloudcallback.getText(), "音频");
        sqfwCloudcallback.setResultDetail(replaceText);
        sqfwCloudcallback.setBusinessType(SqfwCloudBusinessConstants.SERVICE_RECORD);
        if (bean != null) sqfwCloudcallback.setBusinessId(bean.getId());
        sqfwCloudcallbackService.insert(sqfwCloudcallback);

        String completeFlowText = replaceText;
        String code = sqfwCloudcallback.getCode();
        if (!code.equals("0")) {
            completeFlowText = "empty";
        }

        if (StringUtils.isBlank(completeFlowText)) {
            completeFlowText = "empty";
        }

        if (bean != null) {
            bean.setRecording_text(completeFlowText);
            sqfwServicerecordService.updateIgnoreNull(bean);
            sqfwWebSocket.sendMessage(bean.getCreatedBy(), new WebSocketMsgDTO(SqfwWebSocketMsgConstants.service_order_audio_to_text_finish, "语音转文字完成"));
        }
        return Result.success();
    }

    @At("/callbackForCommon")
    @Ok("json")
    @ApiOperation(name = "腾讯云语音识别回调")
    @ApiFormParams(
            implementation = Sqfw_cloudcallback.class
    )
    @ApiResponses
    @SLog(tag = "腾讯云语音识别回调通用",value = "${args[0]}")
    @AdaptBy(type = WhaleAdaptor.class)
    public Result<?> callbackForCommon(@Param("..") Sqfw_cloudcallback sqfwCloudcallback, HttpServletRequest req) {

        System.out.println("工作流语音识别回调：" + sqfwCloudcallback);
        String requestId = sqfwCloudcallback.getRequestId();
        Cnd cnd = Cnd.NEW();
        cnd.and("requestid", "=", requestId);
        Sqfw_cloudcallback querySqfwCloudCallBack = sqfwCloudcallbackService.fetch(cnd);
        if (querySqfwCloudCallBack == null) return Result.error();

        sqfwCloudcallback.setId(querySqfwCloudCallBack.getId());
        sqfwCloudcallback.setCreatedAt(querySqfwCloudCallBack.getCreatedAt());
        sqfwCloudcallback.setDelFlag(false);
        sqfwCloudcallback.setBusinessType(querySqfwCloudCallBack.getBusinessType());
        sqfwCloudcallback.setBusinessId(querySqfwCloudCallBack.getBusinessId());

        String replaceText = sqfwTextReplaceService.replaceText(sqfwCloudcallback.getText(), "音频");
        sqfwCloudcallback.setResultDetail(replaceText);

        String completeFlowText = replaceText;
        String code = sqfwCloudcallback.getCode();
        if (!code.equals("0")) {
            completeFlowText = "empty";
        }

        if (code.equals("0") && StringUtils.isBlank(completeFlowText)) {
            completeFlowText = "empty";
        }

        sqfwCloudcallback.setText(completeFlowText);
        sqfwCloudcallbackService.updateIgnoreNull(sqfwCloudcallback);

        // 根据业务数据更新语音转译的文字内容
        String businessType = sqfwCloudcallback.getBusinessType();

        /* 服务记录 */
        if (businessType.equals(SqfwCloudBusinessConstants.SERVICE_RECORD)) {
            System.out.println("暂时还没有开始做这个功能");
        }


        /* 工作流 */
        if (businessType.equals(SqfwCloudBusinessConstants.FLOW)) {
            String businessId = sqfwCloudcallback.getBusinessId();
            Sqfw_completeflow completeFlow = new Sqfw_completeflow();
            completeFlow.setId(businessId);
            completeFlow.setText(completeFlowText);
            sqfwCompleteflowService.updateIgnoreNull(completeFlow);

            Sqfw_completeflow queryCompleteFlow = sqfwCompleteflowService.fetch(businessId);

            // 使用websocket通知客户端
            sqfwWebSocket.sendMessage(queryCompleteFlow.getUserId(), new WebSocketMsgDTO(SqfwWebSocketMsgConstants.flow_audion_to_text_finish, "工作流语音转换成功"));

            Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(queryCompleteFlow.getSqfwId());
            sqfwWebSocket.sendMessage(serviceRecord.getCreatedBy(), new WebSocketMsgDTO(SqfwWebSocketMsgConstants.flow_audion_to_text_finish, "工作流语音转换成功"));
        }

        /* 普通语音转文字 */
        if (businessType.equals(SqfwCloudBusinessConstants.JUST_AUDIO)) {
            String userId = sqfwCloudcallback.getBusinessId();
            // 普通语音转文字成功
            sqfwWebSocket.sendMessage(userId, new WebSocketMsgDTO(SqfwWebSocketMsgConstants.common_audio_to_text_finish, "普通语音转换成功"));
        }
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改语音识别回调")
    @ApiFormParams(
            implementation = Sqfw_cloudcallback.class
    )
    @ApiResponses
    @SLog(tag = "修改语音识别回调", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> update(@Param("..") Sqfw_cloudcallback sqfwCloudcallback, HttpServletRequest req) {
        sqfwCloudcallback.setUpdatedBy(SecurityUtil.getUserId());
        sqfwCloudcallbackService.updateIgnoreNull(sqfwCloudcallback);
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取语音识别回调")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "获取语音识别回调", value = "${id}")
    @SaCheckLogin
    public Result<?> getData(@Param("id") String id, HttpServletRequest req) {
        Sqfw_cloudcallback sqfwCloudcallback = sqfwCloudcallbackService.fetch(id);
        if (sqfwCloudcallback == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwCloudcallback.setText(AudioToTextUtils.replaceMsgContentNotPrefix(sqfwCloudcallback.getText()));
        return Result.data(sqfwCloudcallback);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除语音识别回调")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除语音识别回调", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> delete(@Param("id") String id, HttpServletRequest req) {
        Sqfw_cloudcallback sqfwCloudcallback = sqfwCloudcallbackService.fetch(id);
        if (sqfwCloudcallback == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwCloudcallbackService.delete(id);
        req.setAttribute("_slog_msg", sqfwCloudcallback.getId());
        return Result.success();
    }

    @At("/uploadCommonAudio")
    @Ok("json")
    @POST
    @SaCheckLogin
    @SLog(tag = "腾讯语音识别",value = "${userId}")
    public Result<?> uploadCommonAudio(@Param("userId") String userId, @Param("fileUrl") String fileUrl) {
        String url = huaweiOssService.getPwdPath(fileUrl);

        String serviceIp = propertiesProxy.get("jarService.ip");
        String port = propertiesProxy.get("server.port");
        String callback = StrFormatter.format("http://{}:{}/platform/sqfw/cloudcallback/callbackForCommon", serviceIp, port);
        Long taskId = TCyysb.Send(url, callback);

        // 往语音回调表中插入一条数据
        String cloudCallBackId = sqfwCloudcallbackService.preInsertSqfwCloudCallBack(SqfwCloudBusinessConstants.JUST_AUDIO, userId, taskId + "");

        return Result.data(cloudCallBackId);
    }
}
